package de.bastian.hinterleitner.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;

import de.bastian.hinterleitner.database.DataHelper;

import android.content.Context;
import android.util.Log;

public class DBCopyHelper {

	public static String DB_FILEPATH = "/data/data/%1/databases/database.db";

	public static boolean exportDatabase(String target, Context c) {

		String dbFilePath = DB_FILEPATH.replace("%1", c.getPackageName());

		String path = new File(target).getParent();
		if(path != null){
			if(!new File(path).mkdirs()){
				Log.d("Filesaving", "cant create "+path);
			}
		}
		
		File from = new File(dbFilePath);
		File to = new File(target);
		if (from.exists()) {
			try {
				copyFile(new FileInputStream(from),
						new FileOutputStream(to));
				return true;
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return false;
	}
	
	public static boolean importDatabase(String origin, Context c) {
		
		if(origin.endsWith(".xml")){
			ArrayList<DataBaseEntry> entries = XmlHelper.loadXml(origin, c);
			DataHelper.getDataHelper(c).createDBfromList(entries);
			return true;
		}

		String dbFilePath = DB_FILEPATH.replace("%1", c.getPackageName());

		// Close the SQLiteOpenHelper so it will commit the created empty
		// database to internal storage.
		DataHelper.getDataHelper(c).close();
		File from = new File(origin);
		File to = new File(dbFilePath);
		if (from.exists()) {
			try {
				copyFile(new FileInputStream(from),
						new FileOutputStream(to));
				// Access the copied database so SQLiteHelper will cache it and
				// mark
				// it as created.
				DataHelper.getDataHelper(c).close();
				return true;
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return false;
	}

	private static void copyFile(FileInputStream fromFile,
			FileOutputStream toFile) throws IOException {
		FileChannel fromChannel = null;
		FileChannel toChannel = null;
		try {
			fromChannel = fromFile.getChannel();
			toChannel = toFile.getChannel();
			fromChannel.transferTo(0, fromChannel.size(), toChannel);
		} finally {
			try {
				if (fromChannel != null) {
					fromChannel.close();
				}
			} finally {
				if (toChannel != null) {
					toChannel.close();
				}
			}
		}
	}
}
